package com.lyn.andplugin.fragment

import android.os.Handler
import android.os.Looper
import android.util.Log
import androidx.appcompat.app.AlertDialog
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.DividerItemDecoration
import com.lyn.andplugin.R
import com.lyn.andplugin.adapter.PluginAdapter
import com.lyn.andplugin.databinding.FragmentPluginBinding
import com.lyn.andplugin.viewModel.PluginViewModel
import com.lyn.pluginhost.PluginHostManager
import com.lyn.ui.fragment.BaseFragment
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch

/**
 *
 * @author longyn 2025/07/10
 * @version 1.0.0
 */
class PluginFragment : BaseFragment<FragmentPluginBinding>() {

    companion object{
        const val TAG = "PluginFragment"
    }

    private lateinit var pluginViewModel: PluginViewModel
    private lateinit var pluginAdapter: PluginAdapter
    private val handler:Handler = Handler(Looper.getMainLooper())

    override fun onMyCreateView() {
        pluginViewModel = ViewModelProvider(this)[PluginViewModel::class.java]
        pluginAdapter = PluginAdapter()
        binding.pluginRecycler.addItemDecoration(DividerItemDecoration(requireContext(),DividerItemDecoration.VERTICAL))
        binding.pluginRecycler.adapter = pluginAdapter
        pluginViewModel.pluginInfoLiveData.observe(this){
            pluginAdapter.setDataList(it,true)
        }
        pluginAdapter.onItemClickListener = { _, _, position ->
            pluginAdapter.getItem(position)?.let { item->
                PluginHostManager.instance.openPlugin(item.pluginInfo.id){}
            }
        }

        pluginAdapter.onItemLongClickListener = { _, _, position ->
            pluginAdapter.getItem(position)?.let { item->
                AlertDialog.Builder(requireContext())
                    .setTitle(getString(R.string.prompt))
                    .setMessage(getString(R.string.are_you_sure_you_want_to_delete))
                    .setNeutralButton(getString(R.string.cancel)
                    ) { dialog, which ->
                        dialog.dismiss()
                    }
                    .setNegativeButton(getString(R.string.confirm)
                    ) { dialog, which ->
                        dialog.dismiss()
                        this@PluginFragment.lifecycleScope.launch(Dispatchers.IO){
                            PluginHostManager.instance.removePlugin(item.pluginInfo.id)
                            pluginViewModel.loadAllPlugin()
                        }
                    }.show()
            }
            true
        }

        pluginViewModel.loadAllPlugin()

    }
}